using System;
using System.ComponentModel.Composition;
using Caliburn.Micro;
using MediaOwl.Common.Messages;

namespace MediaOwl.Common.IsolatedStorage
{
    [Export(typeof(ISettingsManager))]
    public class SettingsManager : ISettingsManager
    {
        private readonly IEventAggregator eventAggregator;
        private const string SettingsFileName = "settings.xml";

        [ImportingConstructor]
        public SettingsManager(IEventAggregator eventAggregator)
        {
            this.eventAggregator = eventAggregator;
            CurrentSettings = new Settings();
        }

        public Settings CurrentSettings { get; private set; }

        public IResult GetSettings(Action<Settings> onSuccess, Action<Exception> onFail = null)
        {
            var result = new DeserializeFromIsolatedStorage<Settings>(SettingsFileName, onSuccess, onFail);

            result.Completed += (s, e) =>
                                    {
                                        if (result.DeserializedValue != null)
                                        {
                                            CurrentSettings = result.DeserializedValue;
                                            eventAggregator.Publish(new SettingsUpdatedMessage(CurrentSettings));
                                        }                               
                                    };

            return result;     
        }

        public IResult SaveSettings()
        {
            var result = new SerializeToIsolatedStorage(CurrentSettings, SettingsFileName);

            result.Completed += (s, e) => eventAggregator.Publish(new SettingsUpdatedMessage(CurrentSettings));

            return result;
        }
    }

    public interface ISettingsManager
    {
        Settings CurrentSettings { get; }
        IResult GetSettings(Action<Settings> onSuccess, Action<Exception> onFail = null);
        IResult SaveSettings();
    }
}